<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="sql," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="什么是Sql注入攻击wiki给出的解释为：
SQL攻击（英语：SQL injection），简称注入攻击，是发生于应用程序之数据库层的安全漏洞。简而言之，是在输入的字符串之中注入SQL指令，在设计不良的程序当中忽略了检查，那么这些注入进去的指令就会被数据库服务器误认为是正常的SQL指令而运行，因此遭到破坏或是入侵。有部分人认为SQL注入攻击是只针对Microsoft SQL Server而来，但只">
<meta property="og:type" content="article">
<meta property="og:title" content="SQL注入">
<meta property="og:url" content="https://zitongchen.github.io/2017/03/31/SQL注入/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="什么是Sql注入攻击wiki给出的解释为：
SQL攻击（英语：SQL injection），简称注入攻击，是发生于应用程序之数据库层的安全漏洞。简而言之，是在输入的字符串之中注入SQL指令，在设计不良的程序当中忽略了检查，那么这些注入进去的指令就会被数据库服务器误认为是正常的SQL指令而运行，因此遭到破坏或是入侵。有部分人认为SQL注入攻击是只针对Microsoft SQL Server而来，但只">
<meta property="og:updated_time" content="2017-04-12T08:32:10.749Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SQL注入">
<meta name="twitter:description" content="什么是Sql注入攻击wiki给出的解释为：
SQL攻击（英语：SQL injection），简称注入攻击，是发生于应用程序之数据库层的安全漏洞。简而言之，是在输入的字符串之中注入SQL指令，在设计不良的程序当中忽略了检查，那么这些注入进去的指令就会被数据库服务器误认为是正常的SQL指令而运行，因此遭到破坏或是入侵。有部分人认为SQL注入攻击是只针对Microsoft SQL Server而来，但只">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/03/31/SQL注入/"/>





  <title> SQL注入 | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/03/31/SQL注入/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                SQL注入
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-31T00:00:00+08:00">
                2017-03-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/sql/" itemprop="url" rel="index">
                    <span itemprop="name">sql</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/03/31/SQL注入/" class="leancloud_visitors" data-flag-title="SQL注入">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="什么是Sql注入攻击"><a href="#什么是Sql注入攻击" class="headerlink" title="什么是Sql注入攻击"></a>什么是Sql注入攻击</h3><p>wiki给出的解释为：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">SQL攻击（英语：SQL injection），简称注入攻击，是发生于应用程序之数据库层的安全漏洞。简而言之，是在输入的</div><div class="line">字符串之中注入SQL指令，在设计不良的程序当中忽略了检查，那么这些注入进去的指令就会被数据库服务器误认为是正</div><div class="line">常的SQL指令而运行，因此遭到破坏或是入侵。</div><div class="line">有部分人认为SQL注入攻击是只针对Microsoft SQL Server而来，但只要是支持批处理SQL指令的数据库服务器，都有</div><div class="line">可能受到此种手法的攻击。</div></pre></td></tr></table></figure>
<p>创建一个数据库</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><div class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`job`</span> (</div><div class="line">  <span class="string">`id`</span> <span class="built_in">varchar</span>(<span class="number">10</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</div><div class="line">  <span class="string">`name`</span> <span class="built_in">varchar</span>(<span class="number">20</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</div><div class="line">  <span class="string">`jobs`</span> <span class="built_in">varchar</span>(<span class="number">20</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span></div><div class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8;</div><div class="line"><span class="comment">/*Data for the table `job` */</span></div><div class="line"><span class="keyword">insert</span>  <span class="keyword">into</span> <span class="string">`job`</span>(<span class="string">`id`</span>,<span class="string">`name`</span>,<span class="string">`jobs`</span>) <span class="keyword">values</span> (<span class="string">'1'</span>,<span class="string">'tony'</span>,<span class="string">'CTO'</span>),(<span class="string">'2'</span>,<span class="string">'zerone'</span>,<span class="string">'CEO'</span>),</div><div class="line">(<span class="string">'3'</span>,<span class="string">'lisa'</span>,<span class="string">'COO'</span>),(<span class="string">'4'</span>,<span class="string">'chan'</span>,<span class="string">'CTO'</span>),(<span class="string">'5'</span>,<span class="string">'tom'</span>,<span class="string">'CEO'</span>),(<span class="string">'6'</span>,<span class="string">'lsi'</span>,<span class="string">'COO'</span>);</div></pre></td></tr></table></figure>
<p>通过普通的查询</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">mysql&gt; select * from job where id = &apos;1&apos;;</div><div class="line">+------+------+------+</div><div class="line">| id   | name | jobs |</div><div class="line">+------+------+------+</div><div class="line">| 1    | tony | CTO  |</div><div class="line">+------+------+------+</div><div class="line">1 row in set (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from job where id = &apos;1&apos; or &apos;1&apos; = &apos;1&apos;;</div><div class="line">+------+--------+------+</div><div class="line">| id   | name   | jobs |</div><div class="line">+------+--------+------+</div><div class="line">| 1    | tony   | CTO  |</div><div class="line">| 2    | zerone | CEO  |</div><div class="line">| 3    | lisa   | COO  |</div><div class="line">| 4    | chan   | CTO  |</div><div class="line">| 5    | tom    | CEO  |</div><div class="line">| 6    | lsi    | COO  |</div><div class="line">+------+--------+------+</div><div class="line">6 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<p>上述虽然不是一个真正的sql注入攻击，但能在一定程度上面体现sql注入攻击的思想。</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">select * from job where id = &apos;1&apos;</div><div class="line">/* 等价于 */</div><div class="line">select * from job where id = &apos;1&apos; or &apos;1&apos; = &apos;1&apos;</div></pre></td></tr></table></figure>
<p><code>or &#39;1&#39; = &#39;1&#39;</code>保持了where条件语句恒真，所以语句变成了</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">select * from job</div></pre></td></tr></table></figure>
<p>因此可以把job表里面的内容全部查询出来</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">mysql&gt; select * from job where id =&apos;1&apos; and jobs = &apos;1&apos;;</div><div class="line">+------+------+------+</div><div class="line">| id   | name | jobs |</div><div class="line">+------+------+------+</div><div class="line">| 1    | tony | CTO  |</div><div class="line">+------+------+------+</div><div class="line">1 row in set (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from job where id = &apos;1&apos; or &apos;1&apos; = &apos;1&apos; -- and jobs;</div><div class="line">+------+--------+------+</div><div class="line">| id   | name   | jobs |</div><div class="line">+------+--------+------+</div><div class="line">| 1    | tony   | CTO  |</div><div class="line">| 2    | zerone | CEO  |</div><div class="line">| 3    | lisa   | COO  |</div><div class="line">| 4    | chan   | CTO  |</div><div class="line">| 5    | tom    | CEO  |</div><div class="line">| 6    | lsi    | COO  |</div><div class="line">+------+--------+------+</div><div class="line">6 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<p>若查询中包含and查询，也是可以通过<code>or &#39;1&#39; = &#39;1&#39; --</code>来进行注入，因为在sql中<code>--</code>表示注释，它会把<code>and</code>条件的第二个条件注释掉</p>
<p>若一个网站使用简单的动态拼接sql语句进行查询，则网站是很容易受到sql注入攻击的</p>
<h3 id="防范SQL注入"><a href="#防范SQL注入" class="headerlink" title="防范SQL注入"></a>防范SQL注入</h3><ol>
<li>不要相信用户的输入，要对用户的输入进行校验，可以通过正则表达式，限制长度或对单引号和“–”进行转换等</li>
<li>不要使用动态拼接SQL，可以使用参数化的SQL或者是直接使用存储过程进行数据查询存储</li>
<li>不要使用管理员权限的数据库连接，为每个应用使用单独的权限有限的数据库连接</li>
<li>不要把机密信息明文存放，请加密或者hash掉密码和敏感的信息</li>
<li>应用的异常信息应该给出尽可能少的提示，最好使用自定义的错误信息对原始错误信息进行包装，把异常信息存放在独立的表中</li>
</ol>
<h4 id="正则表达式校验用户输入"><a href="#正则表达式校验用户输入" class="headerlink" title="正则表达式校验用户输入"></a>正则表达式校验用户输入</h4><p>利用正则表达式校验用户的输入数据中是否包含：单引号和”–”</p>
<p>校验输入数据中是否包含有SQL语句的保留字，如 <code>or</code>,<code>where</code>等</p>
<p>正则表达式只能防范一些常见的SQL Injection，但若有新的攻击方式要对正则表达式进行修改，这显得特别被动，同时吃力不讨好</p>
<h4 id="通过参数化存储过程进行数据查询存取"><a href="#通过参数化存储过程进行数据查询存取" class="headerlink" title="通过参数化存储过程进行数据查询存取"></a>通过参数化存储过程进行数据查询存取</h4><p>参数化存储过程，可以方便查询到是否存在注入的参数是否正确，而且可以控制用户权限；但其也有缺点，一个系统中有那么多大数据库操作，不能每个操作都使用存储过程，同时也不利于维护</p>
<h4 id="参数化SQL语句"><a href="#参数化SQL语句" class="headerlink" title="参数化SQL语句"></a>参数化SQL语句</h4><p>在拼接SQL基础上，一旦恶意SQL代码传递过来，被拼接到SQL语句会被数据库执行，所以可以在SQL语句进行拼接之前进行验证，若条件是数值类型，可以判断输入的是否为数值类型；若条件为字符串类型，可以判断是否包含有空格等</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>在开发中不要相信用户都是好孩子，会按照我们设计的方式走。因此我们必须做出一些措施来防范SQL注入。</p>
<p>参考：<a href="http://www.cnblogs.com/rush/archive/2011/12/31/2309203.html" target="_blank" rel="external">JK_Rush</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/sql/" rel="tag"># sql</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/30/Python知识(一)/" rel="next" title="Python知识(一)">
                <i class="fa fa-chevron-left"></i> Python知识(一)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/31/Python安装Highchart/" rel="prev" title="Python安装Highchart">
                Python安装Highchart <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是Sql注入攻击"><span class="nav-number">1.</span> <span class="nav-text">什么是Sql注入攻击</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#防范SQL注入"><span class="nav-number">2.</span> <span class="nav-text">防范SQL注入</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#正则表达式校验用户输入"><span class="nav-number">2.1.</span> <span class="nav-text">正则表达式校验用户输入</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#通过参数化存储过程进行数据查询存取"><span class="nav-number">2.2.</span> <span class="nav-text">通过参数化存储过程进行数据查询存取</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#参数化SQL语句"><span class="nav-number">2.3.</span> <span class="nav-text">参数化SQL语句</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
